import { useEffect, useRef } from 'react'
import THREEProject from '../utils/index'
const pro = new THREEProject()
const { thr, renderer, scene, axes, controls } = pro
const opt = {
  width: window.innerWidth - 180,
  height: window.innerHeight
}
const geometry = {
  littleBox: new thr.BoxGeometry(2,2,2),
  littleSphere: new thr.SphereGeometry(5, 50, 50)
}
const material = {
  styleRed: new thr.MeshLambertMaterial({ color: Math.random() * 0xffffff })
}

const Full = () => {
  const can = useRef(null)
 
  const perspectiveCameraOpt = [75, opt.width/opt.height, 0.1, 2000]
  const camera = new thr.PerspectiveCamera(...perspectiveCameraOpt)
  camera.position.set(0.01,0.01,0.01)
  pro.setControls(camera)
  let skyBox
  const ambient = new thr.AmbientLight( 0xffffff );
  const group = new thr.Group()
  const init = () => {
    const sphere = new thr.SphereBufferGeometry(500,500,500)
    const texture = new thr.TextureLoader().load('/assets/20190901212441272.jpg')
    const bgMaterial = new thr.MeshBasicMaterial({
      map: texture
    })
    skyBox = new thr.Mesh(sphere, bgMaterial)
    skyBox.geometry.scale( 1, 1, -1 )
    
    for(let i = 0; i < 3000; i++) {
      const mesh = new thr.Mesh(geometry.littleSphere, material.styleRed)
      mesh.position.x = Math.random() * 1000 - 500
      mesh.position.y = Math.random() * 1000 - 500
      mesh.position.z = Math.random() * 1000 - 500
      group.add(mesh)
    }
    
    group.add(skyBox)
    scene.add( group );
    scene.add( ambient );
    console.log("🚀 ~ file: Full.js ~ line 45 ~ init ~ scene", scene)
    appendRenderDom()
    animate()
    initEvent(group)
  }
  const appendRenderDom = () => {
    if(!can.current.children.length) {
    
      can.current.appendChild(renderer.domElement)
    }
  }
  const initEvent = (skyBox) => {
    document.addEventListener('keydown', (event) => {
      const funcMap = {
        'w': () => { skyBox.position.x -= 1 },
        's': () => { skyBox.position.x += 1 }
      }
      if(Object.keys(funcMap).indexOf(event.key) < 0) { return }
      funcMap[event.key]()
    })
  }
  const render = () => {
    controls.update()
    
    renderer.render(scene, camera)
  }

  const animate = () => {
    requestAnimationFrame(animate)
    render()
  }

  useEffect(init, [])

  return (
    <div ref={can}></div>
  )
}

export default Full
export {
  Full
}